﻿using Dapper;
using Hangjing.DBUtility;
using Hangjing.Model;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DapperExtensions;

namespace Hangjing.SQLServerDAL
{
    /// <summary>
    /// 额度操作
    /// </summary>
    public enum LimitOperation
    {
        /// <summary>
        /// 添加
        /// </summary>
        add = 1, //
        /// <summary>
        /// 扣除
        /// </summary>
        sub //
    }


    public class UserShareIncomeDal : BaseDal<user_share_income>
    {

        /// <summary>
        /// 操作额度，判断额度数据，传过来的额度 都是正数，通过 LimitOperation.sub 来设置负数（如果是sub）
        /// </summary>
        /// <param name="record"></param>
        /// <returns></returns>
        public apiResultInfo changeLimit(user_share_income_log record, LimitOperation operation)
        {
            apiResultInfo rs = new apiResultInfo();

            using (SqlConnection cn = new SqlConnection(DBConfig.MasterDBKey))
            {
                cn.Open();
                using (var trans = cn.BeginTransaction())
                {
                    try
                    {

                        user_share_income userLimit = getUserLimit(record.user_id);
                        if (null == userLimit)
                        {
                            userLimit = new user_share_income();
                            userLimit.user_limit = 0;
                        }
                        if (userLimit.user_limit < 0)
                        {
                            rs.state = 0;
                            rs.msg = "额度异常，请联系客服";
                            return rs;
                        }

                        //减积分
                        if (operation == LimitOperation.sub)
                        {
                            if (userLimit.user_limit < Math.Abs(Convert.ToInt32(record.change_limit)))
                            {
                                rs.state = 0;
                                rs.msg = "额度不足,请先购买，或者推荐好友";
                                return rs;
                            }
                            if (record.change_limit > 0) //如果是减的话，这里要是负数
                            {
                                record.change_limit *= -1;
                            }
                        }
                        record.user_limit = userLimit.user_limit;

                        if (userLimit.user_id  == null || userLimit.user_id == 0)
                        {
                            userLimit.user_id = record.user_id;
                            userLimit.user_limit = record.change_limit;
                            userLimit.c_t = DateTime.Now;
                            userLimit.u_t = DateTime.Now;
                            cn.Insert(userLimit, trans);

                            record.user_limit = 0;
                        }
                        else
                        {
                            record.user_limit = userLimit.user_limit;
                    

                            userLimit.user_limit = userLimit.user_limit + record.change_limit;
                            userLimit.u_t = DateTime.Now;
                            cn.Update<user_share_income>(userLimit, trans);

                          
                        }

                      


                        cn.Insert(record, trans);
                        rs.state = 1;

                        trans.Commit();

                        return rs;
                    }
                    catch (Exception ee)
                    {
                        trans.Rollback();
                        Hangjing.AppLog.AppLog.Error("changeLimit:" + ee);
                        rs.state = 0;
                        rs.msg = "系统繁忙，请稍候再试";
                        return rs;
                    }
                }
            }

        }


        /// <summary>
        /// 获取用户的额度
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public user_share_income getUserLimit(int? userid)
        {
            user_share_income limit = new user_share_income();
            using (SqlConnection cn = new SqlConnection(DBConfig.MasterDBKey))
            {
                cn.Open();
                limit = cn.Query<user_share_income>("select Id,user_id,user_limit,c_t,u_t from user_share_income where user_id=@userid ", new { userid = userid }).FirstOrDefault();
                if (limit == null)
                {
                    limit = new user_share_income();
                    limit.user_limit = 0;
                }

                cn.Close();
            }
            return limit;
        }


        /// <summary>
        /// 检查用户额度，确定是否可以交易
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tradePoint"></param>
        /// <returns></returns>
        public apiResultInfo checkLimit(int userId, decimal tradePoint) {

            apiResultInfo rs = new apiResultInfo();
            user_share_income userLimit = getUserLimit(userId);
            if (userLimit.user_limit == null)
            {
                rs.msg = "额度交易不足";
                rs.state = 0;
                return rs;
            }

            if (userLimit.user_limit < tradePoint)
            {
                rs.msg = "额度交易不足";
                rs.state = 0;
                return rs;
            }

            return rs;

        }
    }
}
